package com.qh.resourcehub.sso.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.security.Principal;
@Controller
public class IndexSsoController {
    Logger logger =  LoggerFactory.getLogger(IndexSsoController.class);
    String springApplicationName = "resouce-hub";

    @Value("${cas.client-host-url}")
    String casClientHostUrl;

    @Value("${casClientLogoutUrl}")
    String casClientLogoutUrl;

//    @RequestMapping("/")
//    public String login(Principal user, Model model, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
//        //cas默认单点认证回来，只有userCode。
//        String username = user.getName();
//        logger.info("userCode=" +username);
//        model.addAttribute("userCode", username);
//        session.setAttribute("userCode",username);
//        try {
//            //todo
//
//        } catch (Exception e) {
//
//        }
////        return "redirect:"+casClientHostUrl+"/"+"indexPage";
//
//        return "/index.html";
//    }
        @RequestMapping("/")
        public String login(Principal user, Model model, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
            String username = user.getName();
            logger.info("userCode=" + username);
            model.addAttribute("userCode", username);
            session.setAttribute("userCode", username);
            try {
                // 这里可以做一些其他操作，比如用户信息同步等
            } catch (Exception e) {
                logger.error("Login error", e);
            }

            // 重定向到前端首页，并携带 userCode
            String frontEndUrl = "http://10.181.23.237/index.html#/inventoryManagement/list/Home?userCode="+ username;
            return "redirect:" + frontEndUrl;
        }


    /**
     * 再次重定向，目的去除URL中的jssessionId
     * @return
     */
    @RequestMapping("/indexPage")
    public String indexPage(Model model, HttpSession session) {
        model.addAttribute("userCode", session.getAttribute("userCode"));
        System.out.println(session.getAttribute("userCode"));
        return "/index.html";
    }

    @RequestMapping("/logOut")
    public String loginOut(HttpSession session) {
        session.invalidate();
        return "redirect:" + casClientLogoutUrl;
    }

    @RequestMapping("/url/{url}")
    public String convert(@PathVariable String url){
        return "redirect:"+casClientHostUrl+"/"+springApplicationName+url;
    }

}
